package cn.nawang.ebeim.client.bean;

import java.io.File;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nawang.ebeim.client.util.CommonMethodsUtils;
import cn.nawang.ebeim.client.util.Constants;
import cn.nawang.ebeim.client.util.DbUpDownloadFailedUtil;
import cn.nawang.ebeim.client.util.DbUpDownloadUtil;
import cn.nawang.ebeim.client.util.DbUtil;
import cn.nawang.ebeim.client.util.FileUtil;
import cn.nawang.ebeim.client.util.TransportUtil;
import cn.nawang.ebeim.client.util.UploadProcessBarList;
import cn.nawang.ebeim.client.util.UserBehaviorsUploadUtils;
import cn.nawang.ebeim.client.version.FileInfo;

public class FileBackupTask extends BackupTask {
  private static final Logger LOG = LoggerFactory.getLogger(FileBackupTask.class);

  private FileInfo info;
  /** 原始文件路径 */
  private String srcPath;
  /** 加密文件路径 */
  private String dstPath;

  private String isEncrypt;

  public String getIsEncrypt() {
    return isEncrypt;
  }

  public void setIsEncrypt(String isEncrypt) {
    this.isEncrypt = isEncrypt;
  }

  public FileInfo getInfo() {
    return info;
  }

  public void setInfo(FileInfo info) {
    this.info = info;
  }

  public String getSrcPath() {
    return srcPath;
  }

  public void setSrcPath(String srcPath) {
    this.srcPath = srcPath;
  }

  public String getDstPath() {
    return dstPath;
  }

  public void setDstPath(String dstPath) {
    this.dstPath = dstPath;
  }

  @Override
  public String toString() {
    return "FileBackupTask [info=" + info + ", srcPath=" + srcPath + ", dstPath=" + dstPath + "]";
  }

  @Override
  public void execute() {
    processDataFile(this);
  }

  public void processDataFile(FileBackupTask task) {
    LOG.debug("TODO - processDataFile");
    LOG.info("backup data file {}" + task);
    DataSource ds = task.getDataSource();
    if (CommonMethodsUtils.exists(ds.getId(), task.getInfo().getSignature())) {
      LOG.info("data file already exists, do nothing. {}", task);
      return;
    }

    String srcPath = ds.getRoot() + File.separator + task.getInfo().getPath();
    File file = new File(srcPath + File.separator + task.getInfo().getName());
    if (!file.exists()) {
      LOG.error("file to backup doesn't exists:{}", srcPath + File.separator + task.getInfo().getName());
      return;
    }

    String dstPath = FileUtil.getUploadDataFilePath(getDataSource().getId(), getInfo().getPath());
    File dFile = new File(dstPath);
    if (!dFile.exists()) {
      dFile.mkdirs();
    }

    if (ds.getIsEncrypt().equals(Constants.IS_ENCRYPT_YES)) {
      /** 加密文件 */
      CommonMethodsUtils.encrypt(srcPath, dstPath, task.getInfo().getName());
      DbUtil.updateTaskStatusFile(task.getDataSource().getId(), task.getInfo().getSignature(),
          DbUtil.TASK_STATUS_ENCRYPT);
    } else {
      String fname = task.getInfo().getName();
      /** 直接复制文件 */
      CommonMethodsUtils.copyFile(srcPath + File.separator + fname,
          dstPath + File.separator + fname);
    }
  }

  @Override
  public void upload() {
    LOG.info("upload data file:{}", info);
    String path = FileUtil.getUploadDataFilePath(getDataSource().getId(), info.getPath());
    path += File.separator + info.getName();
    
    if(getIsEncrypt()==null){
      setIsEncrypt(getDataSource().getIsEncrypt());
    }

    String dsId = getDataSource().getId();
    try {
      long beginTime = new Date().getTime();
      if (!new File(path).exists()) {
        UploadProcessBarList.summationTotal(dsId, getInfo().getFileSize());
        DbUpDownloadUtil.updateUploadProcessBarErrorSum(dsId);

        UpDownloadFailedBean bean = new UpDownloadFailedBean();
        bean.setDsId(dsId);
        bean.setRoot(getDataSource().getRoot());
        bean.setPath(info.getPath());
        bean.setName(info.getName());
        bean.setSignature(info.getSignature());
        bean.setType(DbUpDownloadFailedUtil.FAILED_UPLOAD);
        bean.setStatus(DbUpDownloadFailedUtil.STATUS_NEW);
        bean.setTime(new Date().getTime());
        bean.setUid(getDataSource().getCreateUserId());
        bean.setIsEncrypt(getIsEncrypt());
        DbUpDownloadFailedUtil.addUpDownloadFailed(bean);
      } else {
        String[] pathArr = new String[] 
          {
             getDataSource().getRoot(),
             info.getPath(),
             info.getName(),
             String.valueOf(getDataSource().getCreateUserId()),
             getIsEncrypt()
           };
        TransportUtil.uploadDataFile(dsId, info.getSignature(), path, pathArr);
        DbUpDownloadUtil.updateUploadProcessBarOkSum(dsId);
      }
      // 删除临时文件
      // 更新sqlite数据库记录的状态为成功
      DbUtil.updateTaskStatusFile(dsId, info.getSignature(), DbUtil.TASK_STATUS_SUCCESS);
      UserBehaviorsUploadUtils.logToFile(this, dsId, beginTime, UserBehaviorsLog.ACTION_UPLOAD,
          UserBehaviorsLog.STATUS_SUCCESS);
    } catch (Exception e) {
      LOG.error("upload file failed:{}", path, e);
      if (info.getTryCount() != 1) {
        // 更新sqlite数据库记录的状态为断点
        DbUtil.updateTaskStatusFile(dsId, info.getSignature(), DbUtil.TASK_STATUS_BREAK_POINT);
      } else {
        DbUtil.updateTaskStatusFile(dsId, info.getSignature(), DbUtil.TASK_STATUS_SUCCESS);
        DbUpDownloadUtil.updateUploadProcessBarErrorSum(dsId);

        UpDownloadFailedBean bean = new UpDownloadFailedBean();
        bean.setDsId(dsId);
        bean.setRoot(getDataSource().getRoot());
        bean.setPath(info.getPath());
        bean.setName(info.getName());
        bean.setSignature(info.getSignature());
        bean.setType(DbUpDownloadFailedUtil.FAILED_UPLOAD);
        bean.setStatus(DbUpDownloadFailedUtil.STATUS_NEW);
        bean.setTime(new Date().getTime());
        bean.setUid(getDataSource().getCreateUserId());
        bean.setIsEncrypt(getIsEncrypt());
        DbUpDownloadFailedUtil.addUpDownloadFailed(bean);
      }
      // VersionTree tree = VersionTreeUtil.getVersionTree(dsId,
      // getDataSource().getNextVersion().getVersion());
      // tree.findNode(path).setStatus(Node.STSTUS_FAILED);
    }
  }



}
